package com.lbiuse.wx.bean.message.send;

import java.util.List;

import net.sf.json.JSONObject;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 图文消息
 * 
 * @author jinglupeng.cc
 */
public class News implements CustomMessage, PassiveMessage {

	private static final long serialVersionUID = 1L;
	private final String msgType = "news";

	private List<Article> articles;

	public News() {
	}

	public News(List<Article> articles) {
		this.articles = articles;
	}

	public List<Article> getArticles() {
		return articles;
	}

	public void setArticles(List<Article> articles) {
		int len = articles.size();
		for (int i = 10; i < len; i++) {
			articles.remove(i);
		}
		this.articles = articles;
	}

	@Override
	public String toXML(String toUserName, String fromUserName, int createTime) {
		Element root = DocumentHelper.createElement("xml");
		root.addElement("ToUserName").addCDATA(toUserName);
		root.addElement("FromUserName").addCDATA(fromUserName);
		root.addElement("CreateTime").addCDATA(createTime + "");
		root.addElement("MsgType").addCDATA(msgType);
		Element articles = root.addElement("Articles");
		int i = 0;
		for (Article article : getArticles()) {
			Element xml = articles.addElement("item");
			xml.addElement("Title").addCDATA(article.getTitle());
			xml.addElement("Description").addCDATA(article.getDescription());
			xml.addElement("PicUrl").addCDATA(article.getPicurl());
			xml.addElement("Url").addCDATA(article.getUrl());
			if (i++ == 9) {
				break;
			}
		}
		root.addElement("ArticleCount").addCDATA(i + "");
		return root.asXML();
	}

	@Override
	public String toJSON(String touser) {
		JSONObject json = new JSONObject();
		json.put("touser", touser);
		json.put("msgtype", msgType);
		JSONObject json1 = new JSONObject();
		json1.put("articles", getArticles());
		json.put("news", json1);
		return json.toString();
	}

}
